<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-fill-left.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="算法模型," />





  <link rel="alternate" href="/atom.xml" title="我的笔记本" type="application/atom+xml" />






<meta name="description" content="导读你可能又觉得梯度下降是一个完全没有接触过的新词。不过放心，依然能对上。">
<meta property="og:type" content="article">
<meta property="og:title" content="梯度下降">
<meta property="og:url" content="https://sakebow.github.io/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D/index.html">
<meta property="og:site_name" content="我的笔记本">
<meta property="og:description" content="导读你可能又觉得梯度下降是一个完全没有接触过的新词。不过放心，依然能对上。">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E4%BA%8C%E5%85%83%E5%87%BD%E6%95%B0%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D%E6%BC%94%E7%A4%BA.jpg">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E6%A2%AF%E5%BA%A6%E8%AF%B4%E6%98%8E%E5%9B%BE.png">
<meta property="article:published_time" content="2020-07-26T15:23:00.000Z">
<meta property="article:modified_time" content="2020-09-19T00:02:43.308Z">
<meta property="article:author" content="sakebow">
<meta property="article:tag" content="算法模型">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E4%BA%8C%E5%85%83%E5%87%BD%E6%95%B0%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D%E6%BC%94%E7%A4%BA.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://sakebow.github.io/2020/07/26/人工智能/理论基础/梯度下降/"/>



<meta name="google-site-verification" content="gmKmVpWaqN85ipDFNNCd2AweYJjcTFrVxCKCy36wueo" />
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?1d2c90caa02c073d8ebaa116ab3027fb";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


  <title>梯度下降 | 我的笔记本</title>
  








  
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript" src="/js/src/custom.js"></script>
  
<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/sakebow" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub">
	  <svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"
	    style="fill:#64CEAA; color:#fff; position: fixed; top: 0; border: 0; right: 0; z-index: 999;">
	    <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
		<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
		  fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
		<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
		  fill="currentColor" class="octo-body"></path>
	  </svg>
	</a>
	<style>
	  .github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}
	  @keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}
	  @media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}
	</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一只干什么都会失败但是很不想放弃的科研狗</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sakebow.github.io/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sakebow">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/icon/UN.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">梯度下降</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-26T23:23:00+08:00">
                2020-07-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/" itemprop="url" rel="index">
                    <span itemprop="name">人工智能</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.2k字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  15分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="导读"><a href="#导读" class="headerlink" title="导读"></a>导读</h2><p><strong>你可能又觉得梯度下降是一个完全没有接触过的新词。不过放心，依然能对上。</strong></p>
<a id="more"></a>
<h2 id="方向导数和梯度"><a href="#方向导数和梯度" class="headerlink" title="方向导数和梯度"></a>方向导数和梯度</h2><p>在说明怎么进行梯度下降之前，我们需要复习一下方向导数和梯度。</p>
<p>就拿最简单的两个变量为例：</p>
<blockquote>
<p>下图就是一张海拔图。</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/二元函数梯度下降演示.jpg" alt="下降演示"></p>
<p>有一天，你乘坐的飞机失事了，在山顶坠毁，只有你一个人活了下来。弹尽粮绝的你几近绝望。但是你看到眼前有一大片水源，你想着找到了水源就能够活下去。所以你决定在你饿倒、冻死、被野兽咬杀之前，<strong>尽快达到山底的水源</strong>，越快越好。在这种紧急情况下，已经<strong>没有时间让你把所有的路全都探索一遍</strong>了，因为你随时可能在山上出事。</p>
<p>在陡峭的山上，有若干个比较平缓的落脚点。你站在出发的落脚点上，环顾四周，发现了若干能够安全到达的落脚点。于是你在这几个里面选择了最低的一个，跳了过去。接着在下一个落脚点继续寻找更低的落脚点。</p>
</blockquote>
<p>这就是“<strong>下降</strong>”，而<strong>梯度</strong>则是选择一条<strong>最优下降方向</strong>的参考。</p>
<p>所以问题来了，怎么样才能选出<strong>最优下降方向</strong>？如果就只是找遍目力所及的所有落脚点、计算落差，这样当然可行，但是代价太大。所以，我们在这里将使用一定的<strong>数学方法</strong>推算出来。</p>
<p>首先对于在平面$D$（<em>海平面</em>）上具有连续一阶偏导数的二元函数$z=f(x,y)$（<em>山高计算式</em>）上的任意一点，都有一个向量：</p>
<script type="math/tex; mode=display">\vec{grad}f(x,y)=\{\frac{\partial f}{\partial x},\frac{\partial f}{\partial y}\}</script><p>又由于方向导数：</p>
<script type="math/tex; mode=display">\vec{f_L}(x_0,y_0)=({\partial f\over\partial x},{\partial f\over\partial y})\cdot(cos\theta,sin\theta)</script><p>所以，不难得出：</p>
<blockquote>
<p>方向导数是二元函数$z=f(x,y)$在各个方向上的变化量，而当方向导数最大的时候，必定是方向导数和梯度方向重合的时候。而<strong>方向导数最大时</strong>，<strong>函数增长最快</strong>；反之亦然，<strong>方向导数最大时的反方向函数减少最快</strong>。</p>
<p>也就是说，我们在下山的时候唯一需要注意的就是：寻找梯度。</p>
</blockquote>
<p>当然我们还有一些需要注意的细节，<strong>下山的速度</strong>就是其中之一，它有个学术名称叫做<strong>学习率（<em><code>learning rate</code></em>）</strong>，多记为$\eta$。当学习率提高的时候，下山的速率就非常快，很快你就会达到一个区域最优解，但也可能因为步长太大忽略了某个关键点甚至可能导致不收敛；而学习率降低的时候，下山速率就非常低，只不过这样的话你能够找到更多的落脚点，从而一定程度上减少了陷入局部最优解的可能。</p>
<p>拿下面这个图举个例子：</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/梯度说明图.png" alt="梯度说明"></p>
<p>很清楚地看到，在$x\in(0,1)$和$x\in(4,5)$的时候，函数下降速度和上升速度都非常快，这个时候可以<strong>适当减少学习率</strong>，就像是<strong>单机FPS游戏里放慢步伐寻找隐藏点</strong>一样，避免错过了任何一个细节。但是过小的步伐会导致收敛速度非常慢，一直再重复无效的学习；而在$x\in(1,4)$的时候，函数不管是上升还是下降都非常缓慢，基本没有什么起伏，可以<strong>适当加快步伐</strong>，就像是<strong>GalGame二刷回收CG</strong>一样，只抓重点，忽略细节。但是过大的步伐会导致你忽略掉$x\in(3,4)$的极值点。</p>
<p>总的来说，<strong>步长小了可能会陷入局部最优解；而步长大了可能会离最优解越来越远，最终得出错误的结果</strong>。</p>
<p><em>不过呢，三维我们还能勉强想象，但是拓展到四维、五维等超越3个维度的坐标系时，作为三次元的我们将无法想象那样的存在。所以，我们目前所能做的极限就是讨论三元变量的关系了。有没有三维以上的方向导数解法？当然有，本篇说明的就是<strong>通用解法</strong>，只不过对于三维以上的数据就<strong>无法说明几何意义</strong>了。</em></p>
<h2 id="梯度下降是什么"><a href="#梯度下降是什么" class="headerlink" title="梯度下降是什么"></a>梯度下降是什么</h2><p>经过复习，聪明的你应该能够明白，所谓梯度下降即是：</p>
<ul>
<li><p>从图像的意义上来看，就可以总结为：任意选取一个落脚点，然后搜索周边看能不能找到更低的落脚点。这个点不出意外的话应该在梯度方向的反方向上。</p>
</li>
<li><p>从数学的意义上来看，就可以总结为：任意选取<strong>损失函数</strong>上的一个点，一步一步寻找区域极值，并坚信其中一个极值是全域最小值，逐渐逼近使得<strong>损失函数</strong>的值最小的点。</p>
</li>
</ul>
<p><em>数学的角度听起来有点贪心算法的味道了？有一说一，确实。当然，不出意外的话，极值中确实会有最值；只不过时常会有意外，也就是说，最值不在极值中，而是在边界。</em></p>
<p>“<strong>不识庐山真面目，只缘身在此山中</strong>”。这也正是贪心算法的“贪心”所在啊，偏偏想要<strong>使用最少的次数碰运气似的找到最优解</strong>。实际上，你朝梯度的反方向看到的“<strong>最低点</strong>”，也仅仅是通过一般的数学计算才出现的<strong>预测的点</strong>，实际最低点甚至可能出现在<strong>任何地方</strong>。虽然异常的尴尬，但这也正是贪心算法想要解决的，不是么？起码7位数的数据遍历起来实在是有点难受啊……</p>
<h2 id="为什么选择梯度下降"><a href="#为什么选择梯度下降" class="headerlink" title="为什么选择梯度下降"></a>为什么选择梯度下降</h2><p>这个方法不仅用于线性方程求解，而且还适用于机器学习的很多个领域。找到代价函数最小值和各维度的值，同时找出根据很多自变量变化的因变量拟合函数，可以在非常多的方面说明问题，比如<strong>决策</strong>、<strong>推荐</strong>、<strong>预测</strong>、<strong>分类</strong>等等。</p>
<p>其实最重要的是，他能够用比较低的时间复杂度找到最好的一个解。这对于信息爆炸式增长的今天是非常有必要的。中国14亿人，就算只有一半的网民，也是7亿的并发量；面对这7亿用户的偏好分析，实在是等不起十几天慢慢磨出一份精简的报告。</p>
<h2 id="随机梯度下降"><a href="#随机梯度下降" class="headerlink" title="随机梯度下降"></a>随机梯度下降</h2><p>好了，现在开始进入正题：梯度下降的步骤。</p>
<p>我们先不要弄得太复杂，还是老例子：</p>
<blockquote>
<p>时间回溯到你研究猫娘食量那会。你确确实实拿到了20万数据，每个数据都是以（年龄，食量）这样的坐标形式出现。这看起来没什么问题，只不过你突然发现猫娘们的食量增长速度在成年之后随着年龄的增长而不断趋于平稳，成年之前却疯狂增长。你觉得线性方程不再适用。这样的函数你似乎希望是对数函数，可是这是不是因为有其他因素的影响？</p>
<p>于是，你凭着对猫娘疯狂的热爱，开始了第二波数据收集。这次你拿到了年龄(age)、身高(height)、体重(weight)和食量(quantity)四个数据，构成了函数$Q=f(a,h,w)$。</p>
</blockquote>
<p>这次涉及了三个维度和一个自变量，虽然复杂了很多，但也勉强能够画出来。只不过梯度下降的图像意义便不再是<strong>下山</strong>了，而是构建一个平面或者瞄准某一个中心。</p>
<blockquote>
<p><del>你凭着自己的性癖</del>……你随机选择了一位猫娘，将她的数据使用矩阵形式记录了下来：</p>
<script type="math/tex; mode=display">neko_0=\left[\begin{matrix}
  a_0\\h_0\\w_0
\end{matrix}\right]</script><p>紧接着，下一个数据就是：</p>
<script type="math/tex; mode=display">neko_1=\left[\begin{matrix}
  a_1\\h_1\\w_1
\end{matrix}\right]
=\left[\begin{matrix}
  a_0\\h_0\\w_0
\end{matrix}\right]
-\eta\left[\begin{matrix}
{\partial\over\partial a} f(a_0,h_0,w_0)\\
{\partial\over\partial h} f(a_0,h_0,w_0)\\
{\partial\over\partial w} f(a_0,h_0,w_0)
\end{matrix}\right]</script></blockquote>
<p>当然，$neko_1$是有实际数值的，而使用<code>学习率</code>、$neko_0$和<code>损失函数的偏导数</code>计算出来的$neko_1$并不是真实的数据。那么使用哪一个数据？当然是都使用。因为现在猫娘的食量和年龄变成了非线性关系，也就是说在<strong>x取值范围同样长的情况下</strong>，不同取值范围中函数的<strong>变化量不一样</strong>，部分密集，部分稀疏。所以应对<strong>密集部分</strong>我们需要<strong>加大学习率</strong>，尽快过渡到稀疏部分，从而减少重复学习的时间；应对<strong>稀疏部分</strong>我们要<strong>减少学习率</strong>，尽量避免忽略了重要区间的情况。</p>
<blockquote>
<p>好了，现在你通过数学计算拿到了$neko_1$，于是你准备获取$neko_2$。同样的，代入公式：</p>
<script type="math/tex; mode=display">neko_2=\left[\begin{matrix}
  a_2\\h_2\\w_2
\end{matrix}\right]
=\left[\begin{matrix}
  a_1\\h_1\\w_1
\end{matrix}\right]
-\eta\left[\begin{matrix}
{\partial\over\partial a} f(a_1,h_1,w_1)\\
{\partial\over\partial h} f(a_1,h_1,w_1)\\
{\partial\over\partial w} f(a_1,h_1,w_1)
\end{matrix}\right]</script><p>经过一番辛苦，你也得出来了这个数据。但是你实在算不下去了，虽然对猫娘包含热情，但是在完全机械的计算过程中，再怎么高涨的热情都会逐渐被消耗殆尽。于是你希望计算机能够帮助运算，便大致写下了一串伪代码：</p>
<p><code>repeat until convergence {</code></p>
<script type="math/tex; mode=display">\left[\begin{matrix}
  a_i\\h_i\\w_i
\end{matrix}\right]
:=
\left[\begin{matrix}
  a_i\\h_i\\w_i
\end{matrix}\right]
-\eta
\left[\begin{matrix}
  {\partial\over\partial a} f(a_i,h_i,w_i)\\
  {\partial\over\partial h} f(a_i,h_i,w_i)\\
  {\partial\over\partial w} f(a_i,h_i,w_i)
\end{matrix}\right]</script><p><code>}</code></p>
</blockquote>
<p><em>伪代码中<code>=</code>和<code>:=</code>略有区别，分别是<strong>相等</strong>和<strong>赋值</strong>的意思</em></p>
<p>这样看似乎没有什么大问题，但是在实际代码实现中，我们尤其需要注意一个很难注意到的细节：</p>
<p><strong>这个矩阵形式的写法意味着$a_i$、$h_i$、$w_i$是同步更新的！！！</strong></p>
<p><strong>这个矩阵形式的写法意味着$a_i$、$h_i$、$w_i$是同步更新的！！！</strong></p>
<p><strong>这个矩阵形式的写法意味着$a_i$、$h_i$、$w_i$是同步更新的！！！</strong></p>
<p>重要的事情说三遍！如果不是同步的话，<strong>错误的梯度下降</strong>伪代码将会变成这样：</p>
<blockquote>
<p><code>repeat until convergence {</code></p>
<script type="math/tex; mode=display">
 temp_a={\partial\over\partial a} f(a_i,h_i,w_i)\cdots①\\
 a_i = temp_a\\
 temp_h={\partial\over\partial h} f(a_i,h_i,w_i)\cdots②\\
 \ldots</script><p><code>}</code></p>
</blockquote>
<p>注意到了吗？①式和②式中，$a_i$的值不同了！这是严重的逻辑错误！</p>
<p><strong>正确的梯度下降</strong>伪代码就应该是这样：</p>
<blockquote>
<p><code>repeat until convergence {</code></p>
<script type="math/tex; mode=display">
 temp_a=a_i-\eta{\partial\over\partial a} f(a_i,h_i,w_i)\\
 temp_h=h_i-\eta{\partial\over\partial h} f(a_i,h_i,w_i)\\
 temp_w=w_i-\eta{\partial\over\partial w} f(a_i,h_i,w_i)\\
 a_i = temp_a\\
 h_i = temp_h\\
 w_i = temp_w</script><p><code>}</code></p>
</blockquote>
<p><strong>要么全部修改，要么全不修改</strong>。像极了数据库的<strong>原子性</strong>不是么？</p>
<p><em>在说明时我强调了是<strong>错误的梯度下降伪代码</strong>，而不是<strong>错误的伪代码</strong>，这是因为这本来就是一种正确的算法，但不是梯度下降，而是一种其他的什么代码。这就要各位读者继续读下去来寻找正确答案了。</em></p>
<p>没错，这就是通用解法，无论多少维，用这个矩阵解法都会有一个结果。随着学习的进行，导数或者偏导数都会逐渐变化，$\eta$也应当随之而变化。他也有另外一个名字，叫<strong>随机梯度下降</strong>，因为我们刚刚是随机选择初始点、根据梯度寻找下一跳、逐步靠近最优解，所以收敛的时候有很大的随机性，收敛时也会在局部最优附近疯狂抖动。还是用个反常的例子类比：</p>
<blockquote>
<p>你的猫娘很生气，你想逗她开心。你身边有很多东西，毛球、老鼠玩具、吉他、钢琴等等。你知道这些她都喜欢，但是你不知道这次怎么样才能让她开心。于是你开始疯狂试探。</p>
<p>有时候她笑了一下，有时候又挠你几下，有时候保持冷漠……在心情在变好和变坏之间反复横跳。最后，你终于拿出口琴吹起了她喜欢的音乐，把她哄好了。</p>
</blockquote>
<p>当然，公式归公式，解法是解法，这两个可以不需要严格意义上保持一致。也就是说，如果$f(a,h,w)$在求导的时候极大地增加了复杂度，就比如$\sqrt{\frac{1+sinx}{1-cosx}}$，我们可以人为地分段、化简，变成方便计算的其他公式，就像吴恩达教授的视频课程中将线性方程$Y=\beta_0+\beta_1x$中待定系数的求解从二次通过求导降为一次。（<em>如果你不清楚为什么是二次，请查看我之前写的<a href="/2020/07/26/人工智能/算法模型/代价函数">代价函数</a>一文</em>）</p>
<h2 id="一个尴尬的细节"><a href="#一个尴尬的细节" class="headerlink" title="一个尴尬的细节"></a>一个尴尬的细节</h2><p>好了，到了这里，相信各位读者对梯度下降也有一定的了解了。那么，各位有没有注意到一个小小的细节：<strong>我们是为什么需要根据一定的步长移动</strong>？其实是基于“<strong>最初随机选到的点并不是极值点</strong>”这一前提下展开的。那么我们就极端一点，最初就那么运气不好，选到了极值点，会怎么样呢？很显然，极值点的导数或偏导数都是0，最终我们的计算式也就化简成为了：</p>
<script type="math/tex; mode=display">\left[\begin{matrix}
  a_i\\h_i\\w_i
\end{matrix}\right]
:=
\left[\begin{matrix}
  a_i\\h_i\\w_i
\end{matrix}\right]
-\eta
\left[\begin{matrix}
  {\partial\over\partial a} f(a_i,h_i,w_i)\\
  {\partial\over\partial h} f(a_i,h_i,w_i)\\
  {\partial\over\partial w} f(a_i,h_i,w_i)
\end{matrix}\right]
=
\left[\begin{matrix}
  a_i\\h_i\\w_i
\end{matrix}\right]
-\eta\times0=
\left[\begin{matrix}
  a_i\\h_i\\w_i
\end{matrix}\right]</script><p>也就是说在这里我们将原地踏步。如果这里并不是全域最优解，而是局部最优解，我们也就像一开始介绍梯度下降是所说的一样：<strong>陷入局部最优解</strong>。这也正是<strong>步长过小</strong>造成的<strong>必然结果</strong>。</p>
<p>当然，既然有让你陷入局部最优解的情况，也有只能收敛到全局最优解的情况。用比较学术一点的话来说，就是“<strong>目标函数$f(a,h,w)$是一个凹函数</strong>”（<em>国外这里叫<strong>凸函数</strong>，因为看的方向不一样所以叫法不一样</em>），即目标函数的二阶偏导数<strong>恒大于0</strong>。这就导致一阶偏导数最多也就1个零点，即最多有一个极值，原函数要么是个碗，极值即最值；要么就单调，端点是最值。</p>
<p>很尴尬，也很无奈。当然办法还是有的，也就是<strong>贪心算法</strong>。这就依靠大家打怪升级之后解锁新篇章了，这里只介绍这么多有关梯度的内容。</p>
<h2 id="批量（Bacth）梯度下降"><a href="#批量（Bacth）梯度下降" class="headerlink" title="批量（Bacth）梯度下降"></a>批量（<code>Bacth</code>）梯度下降</h2><p>我相信你会等不及找答案的。所以这里提供一个临时的解决办法：批量梯度下降。</p>
<p>为什么是批量？在这里我们每次迭代都会整个训练集都试一遍，然后找到一个局部最优解，然后剪枝，重新遍历整个数据集，然后又找到下一个局部最优解，再剪枝……整个过程将会行走在非常标准的直通线路上。</p>
<p>当然，缺点也非常明显，整个训练一遍意味着需要大量的内存和大量的计算。如果训练集足够大，内存将无法一次性执行完，要么直接<code>OutOfMemoryException</code>，要么在内存加载的内容全部计算完后等待磁盘经过漫长的时间加载所需的下一批数据。整体来说还是相当的憋屈，所以也在逐渐的弃用这个方法。</p>
<p>是不是有点能理解了呢？</p>
<h2 id="附录"><a href="#附录" class="headerlink" title="附录"></a>附录</h2><p>在吴恩达教授的课程中，解向量是这么求的：</p>
<script type="math/tex; mode=display">
\left[\begin{matrix}
  a_i\\h_i\\w_i
\end{matrix}\right]
:=
\left[\begin{matrix}
  a_i\\h_i\\w_i
\end{matrix}\right]
-\eta
\left[\begin{matrix}
  {\partial\over\partial a} f(a_0,h_0,w_0)\\
  {\partial\over\partial h} f(a_0,h_0,w_0)\\
  {\partial\over\partial w} f(a_0,h_0,w_0)
\end{matrix}\right]</script><p>其中在循环之中不停调整$a_0$、$h_0$、$w_0$的值。实际上这么做的核心目的依然是保持同步，只不过用本篇所讲述的方法是普遍都在使用的方法，因为看起来更简洁。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>代码滞销，救救码农</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/wechatpay.png" alt="sakebow 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/alipay.jpg" alt="sakebow 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    sakebow
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://sakebow.github.io/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D/" title="梯度下降">https://sakebow.github.io/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E7%AE%97%E6%B3%95%E6%A8%A1%E5%9E%8B/" rel="tag"> <i class="fa fa-tag"></i> 算法模型</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E5%BB%BA%E6%A8%A1%E5%B7%A5%E5%85%B7%EF%BC%9Aoctave/" rel="next" title="建模工具：octave">
                <i class="fa fa-chevron-left"></i> 建模工具：octave
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/08/01/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E5%A4%9A%E5%85%83%E6%A2%AF%E5%BA%A6%E5%87%BD%E6%95%B0%E7%9A%84%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D/" rel="prev" title="多元梯度函数的梯度下降">
                多元梯度函数的梯度下降 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>
	<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
    <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
	<script>
      var gitment = new Gitment({
        id: '<%= page.date %>',
        owner: 'sakebow',
        repo: 'git@github.com:sakebow/sakebow.github.io.git',
        oauth: {
          client_id: '5c74c5e1b67e5a5adbdf',
          client_secret: '0d352353407a32cee695d8ac619108e725919c57',
        },
      });
      gitment.render('gitment-container');
    </script>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/icon/UN.png"
                alt="sakebow" />
            
              <p class="site-author-name" itemprop="name">sakebow</p>
              <p class="site-description motion-element" itemprop="description">哪怕是狗也不想随随便便放弃看到的骨头</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">70</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sakebow" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sakebowljx@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/sakebow" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i>Google</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/sakebow" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/sakebow" title="Sakebow的GitHub" target="_blank">Sakebow的GitHub</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.appgofast.com" title="我喜欢的VPN" target="_blank">我喜欢的VPN</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#导读"><span class="nav-number">1.</span> <span class="nav-text">导读</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#方向导数和梯度"><span class="nav-number">2.</span> <span class="nav-text">方向导数和梯度</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#梯度下降是什么"><span class="nav-number">3.</span> <span class="nav-text">梯度下降是什么</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么选择梯度下降"><span class="nav-number">4.</span> <span class="nav-text">为什么选择梯度下降</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#随机梯度下降"><span class="nav-number">5.</span> <span class="nav-text">随机梯度下降</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一个尴尬的细节"><span class="nav-number">6.</span> <span class="nav-text">一个尴尬的细节</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#批量（Bacth）梯度下降"><span class="nav-number">7.</span> <span class="nav-text">批量（Bacth）梯度下降</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#附录"><span class="nav-number">8.</span> <span class="nav-text">附录</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Sakebow</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'sakebow',
            repo: 'git@github.com:sakebow/sakebow.github.io.git',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '0d352353407a32cee695d8ac619108e725919c57',
            
                client_id: '5c74c5e1b67e5a5adbdf'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
 
</body>
</html>
